package cn.jingyuan.owl.enums.mybatis;

import cn.jingyuan.owl.enums.core.EnumString;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class EnumStringTypeHandler<E extends Enum<?> & EnumString> extends BaseTypeHandler<EnumString> {

    private final Class<E> type;

    public EnumStringTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, EnumString parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getCode());
    }

    @Override
    public EnumString getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return this.valueOf(value);
    }

    @Override
    public EnumString getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return this.valueOf(value);
    }

    @Override
    public EnumString getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return this.valueOf(value);
    }

    private E valueOf(String value) {
        try {
            return EnumString.valueOf(value, type);
        } catch (Exception ex) {
            throw new IllegalArgumentException("Cannot convert [ " + value + "] to" + type.getSimpleName() + " by value value.", ex);
        }
    }

}
